#include "httpserver.h"
#include <QDebug>

HttpServer::HttpServer(QObject *parent) : QObject(parent)
{
    session = NULL;
    server = new QTcpServer();
    connect(server, SIGNAL(newConnection()), this, SLOT(newTaskSession()));
    server->listen(QHostAddress::Any, 6002);
    qDebug()<<"[HttpServer]6002 listening...";
}

TempCase *HttpServer::getDevCase(QString devId)
{
    TempMain* par = static_cast<TempMain*>(parent());
    return par->getDevCase(devId);
}

void HttpServer::newTaskSession()
{
    if(server->hasPendingConnections())
    {
        QTcpSocket* socket = server->nextPendingConnection();
        if(session == NULL)
        {
            session = new TaskSession(socket, this);
            connect(session, SIGNAL(sessionFinished()), this, SLOT(deleteTastSession()));
            connect(session, SIGNAL(updateDevInfo(QString)), this, SIGNAL(updateDevInfo(QString)));
        }
        else
        {
            session->setSocket(socket);
        }
//        connect(thread, SIGNAL(finished()), session, SLOT(deleteLater()));
//        connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
//        thread->start();
        qDebug()<<"HttpServer::newTaskSession";
    }
}

void HttpServer::deleteTastSession()
{
    session->deleteLater();
    session = NULL;
}
